﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DoubleH.Plugins;
using Table = FCNS.Data.Table;
using System.Data;
using System.ComponentModel;
using DoubleH.Utility;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility.Configuration;
using DoubleH.Utility.IO;
using FCNS.Data;

namespace DoubleH
{
    public partial class WorkArea : Window
    {
        private void InitToolBarTopUI()
        {
            var overflowGrid = toolBarTop.Template.FindName("OverflowGrid", toolBarTop) as FrameworkElement;
            if (overflowGrid != null)
                overflowGrid.Visibility = Visibility.Collapsed;

            var mainPanelBorder = toolBarTop.Template.FindName("MainPanelBorder", toolBarTop) as FrameworkElement;
            if (mainPanelBorder != null)
                mainPanelBorder.Margin = new Thickness(0);
        }

        private void NewObj()
        {
            if (selectedMenu == null)
                return;

            selectedMenu.DataTable = null;
            pluginManager.LoadPlugin(DbDefine.baseDir + selectedMenu.DllFile, null, selectedMenu.TableText, selectedMenu.DataTable, selectedMenu.Tag);
        }

        //private void PreObj()
        //{
        //    if (int.Parse(labelIndex1.Content.ToString()) == 1)
        //        return;

        //    uint start = uint.Parse(labelIndex1.Content.ToString()) - DoubleHConfig.UserConfig.GroupDataCount;
        //    labelIndex1.Content = start;
        //    labelIndex2.Content = (start - 1 + DoubleHConfig.UserConfig.GroupDataCount);
        //    BeginBindData();
        //}

        //private void NextObj()
        //{
        //    int count = uCPagePanel1.Items.Count;
        //    if (count < DoubleHConfig.UserConfig.GroupDataCount)//如果列表已经没有项目就别搜索了
        //        return;

        //    labelIndex1.Content = (int.Parse(labelIndex1.Content.ToString()) + DoubleHConfig.UserConfig.GroupDataCount);
        //    BeginBindData();
        //    labelIndex2.Content = (int.Parse(labelIndex2.Content.ToString()) + (count < DoubleHConfig.UserConfig.GroupDataCount ? count : (int)DoubleHConfig.UserConfig.GroupDataCount));
        //}

        private void EditObj()
        {
            selectedMenu.DataTable = uCPagePanel1.SelectedItem as FCNS.Data.Table.DataTableS;
            pluginManager.LoadPlugin(DbDefine.baseDir + selectedMenu.DllFile, null, selectedMenu.TableText, selectedMenu.DataTable, "Edit");
        }

        private void SearchObjByWindow()
        {
            if (selectedMenu == null)
                return;

            DoubleH.Utility.Search.WindowSearch so = new DoubleH.Utility.Search.WindowSearch();
            so.Init(selectedMenu, uCPagePanel1.Items.GetType().GetGenericTypeDefinition());
            so.ShowDialog();
            if (so.Items != null)
                uCPagePanel1.LoadData(null, so.Items);
        }

        private void SearchObjByText()
        {
            if (selectedMenu == null)
                return;

            if (string.IsNullOrEmpty(textBoxSearch.Text))
            {
                BeginBindData();
                return;
            }

            StringBuilder sb = new StringBuilder();
            selectedMenu.UserParams.Items.ForEach(f =>
            {
                if (f.CanSearch)
                    sb.Append(f.BindingName + ",");
            });
            DoubleH.Utility.Search.SearchUtility su = new Utility.Search.SearchUtility();
            uCPagePanel1.LoadData(null, su.Search(uCPagePanel1.Items, textBoxSearch.Text, sb.ToString().Split(',')));
        }

        private void OpenHelp()
        {
            System.Diagnostics.Process.Start("http://www.fcnsoft.com/download.html");
            //expanderMore.Height = 196;
        }

        private void Print()
        {
            FCNS.Data.Interface.IOrder order = uCPagePanel1.SelectedItem as FCNS.Data.Interface.IOrder;
            if (order == null)
            {
                MessageWindow.Show("请选择需要打印的单据");
                return;
            }

            DoubleH.Utility.Print.PrintForm.ShowPrint(uCPagePanel1.SelectedItem as FCNS.Data.Interface.IDataTable, selectedMenu.TableText, string.Empty);
        }

        private void PrintList()
        {
            uCPagePanel1.Mode = Utility.UC.UCPagePanel.EnumMode.列表;
            DoubleH.Utility.Print.PrintForm.ShowPrintList(uCPagePanel1.DataGridObj);
        }

        private void EventImport()
        {
            DoubleH.Utility.IO.FileTools ft = new FileTools();
            if (selectedMenu == null)
                return;

            DataTable table = ft.ImportFileToDataTable(selectedMenu.TableName, null);
            if (table == null)
                return;

            int error = 0, right = 0;
            DoubleH.Utility.IO.FileTools fts = new FileTools();
            foreach (DataRow row in table.Rows)
            {
                FCNS.Data.Interface.IDataImport idi = fts.CreateInstance(selectedMenu.TableName);
                foreach (System.Reflection.PropertyInfo info in idi.GetType().GetProperties())
                {
                    if (!table.Columns.Contains(info.Name))
                        continue;
                    try
                    {
                        switch (info.PropertyType.ToString())
                        {
                            case "System.String": info.SetValue(idi, row[info.Name], null); break;
                            case "System.Int64": info.SetValue(idi, Convert.ToInt64(row[info.Name]), null); break;
                            case "System.Double": info.SetValue(idi, Convert.ToDouble(row[info.Name]), null); break;
                            case "System.Boolean": info.SetValue(idi, Convert.ToBoolean(row[info.Name]), null); break;
                        }
                    }
                    catch { }
                }

                Table.DataTableS.EnumDatabaseStatus result = idi.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    right += 1;
                else
                    error += 1;
            }
            MessageWindow.Show(right + " 条数据导入成功," + error + " 条数据导入失败.");
        }

        private void EventExport()
        {
            DoubleH.Utility.IO.FileTools ft = new FileTools();
            ft.ExportDataGridToFile(uCPagePanel1.DataGridObj, string.Empty);
        }

        private void EventZuoFei()
        {
            if (selectedMenu.Authority < Table.UserS.EnumAuthority.作废)
            {
                MessageWindow.Show("权限不足");
                return;
            }

            if (MessageWindow.Show("", "确定要作废选中项目吗?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;

            switch (selectedMenu.TableText)
            {
                case DataTableText.POS禁售商品:
                    Table.ProductS ps = uCPagePanel1.SelectedItem as Table.ProductS;
                    if (ps != null)
                    {
                        ps.UpdatePosCanNotUseList(string.Empty);
                    }
                    break;

                default:
                    FCNS.Data.Interface.IDataTable table = uCPagePanel1.SelectedItem as FCNS.Data.Interface.IDataTable;
                    if (table != null)
                        MessageWindow.Show(table.ZuoFei().ToString());

                    break;
            }
            BeginBindData();
        }

        //private void EventZuoFei()
        //{
        //    if (MessageWindow.Show("", "确定要停用/作废选中项目吗?", MessageBoxButton.YesNo) == MessageBoxResult.No)
        //        return;

        //    if (selectedMenu.TableText == DataTableText.Pos禁售商品)
        //    {
        //        Table.ProductS ps = uCPagePanel1.SelectedItem as Table.ProductS;
        //        if (ps != null)
        //            ps.SetPosCanNotUseList(false);
        //    }
        //    else
        //    {
        //        int i = 0;
        //        foreach (object obj in uCPagePanel1.SelectedItems)
        //        {
        //            FCNS.Data.Interface.IDataTable table = obj as FCNS.Data.Interface.IDataTable;
        //            if (table != null)
        //                if (table.ZuoFei() == Table.DataTableS.EnumDatabaseStatus.操作成功)
        //                    continue;

        //            i++;
        //        }
        //        if (i != 0)
        //            MessageWindow.Show(i.ToString() + " 张单据存在业务来往,无法删除");
        //    }
        //}

        private void ExpanderConfigOpen()
        {
            expanderConfig.Cursor = Cursors.Hand;
            //expanderConfig.Height = 131;
        }

        private void ExpanderConfigClose()
        {
            expanderConfig.Cursor = Cursors.Arrow;
            expanderConfig.IsExpanded = false;
            //expanderConfig.Height = 25;
        }

        private void OpenSysconfig()
        {
            pluginManager.LoadPlugin(DbDefine.baseDir + "SysConfig.dll", null, DataTableText.系统配置, null, null);
        }

        private void LoginOff()
        {
            DoubleH.Utility.Net.NetUtility.LanClient.OffLine();
            HideMessageForm();
            ConfigSerializer.SaveConfig(DoubleHConfig.UserConfig, Table.UserS.LoginUser.Id);
            this.Hide();
            if (!DoubleH.Utility.Login.LoginUtility.ShowLoginWindowSuccess(Table.UserS.EnumFlag.操作员))
            {
                System.Environment.Exit(0);
                return;
            }
            else
            {
                //InitUserVar();
                ShowMessageForm();
                DoubleH.Utility.Net.NetUtility.StartNet();
                this.Show();
            }
        }

        private void PrintConfig()
        {
            DoubleH.Utility.Print.PrintConfig pc = new Utility.Print.PrintConfig();
            DoubleH.Utility.Configuration.PrintConfig config = DoubleHConfig.AppConfig.PrintConfigItems.FirstOrDefault(f => f.TableText == selectedMenu.TableText.ToString());
            if (config == null)
                DoubleHConfig.AppConfig.PrintConfigItems.Add(config = new PrintConfig() { TableText = selectedMenu.TableText.ToString() });

            pc.Init(config);
            pc.ShowDialog();
        }

        private void OpenCalc()
        {
            System.Diagnostics.Process.Start("calc.exe");
        }


        private void PagePanelItemClick(object item)
        {
            switch (selectedMenu.TableText)
            {
                case DataTableText.采购物流跟踪:
                case DataTableText.批发物流跟踪:
                case DataTableText.仓库物流跟踪:
                    //if (cell.Column != null && cell.Column.Header.ToString() == "状态")
                    Table.WuLiuS ws = item as Table.WuLiuS;
                    if (ws != null)
                        Process.Start(ws._Http);

                    break;

                case DataTableText.项目列表:
                    Table.ProjectS ps = item as Table.ProjectS;
                    if (ps != null)
                        Process.Start(ps.Url);

                    break;
            }
        }

        private void PagePanelItemDoubleClick()
        {
            switch (selectedMenu.TableText)
            {
                case DataTableText.POS机器号:
                    Table.PosS pos = uCPagePanel1.SelectedItem as Table.PosS;
                    switch (pos.Enable)
                    {
                        case Table.PosS.EnumEnable.启用:
                            if (MessageWindow.Show("", "确定要停用 " + pos.PosNO + " 吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                pos.UpdateTo(Table.PosS.EnumEnable.停用);
                            break;
                        case Table.PosS.EnumEnable.评估:
                            if (MessageWindow.Show("", "确定要审核 " + pos.PosNO + " 吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                pos.UpdateTo(Table.PosS.EnumEnable.启用);
                            break;
                        case Table.PosS.EnumEnable.停用:
                            if (MessageWindow.Show("", "确定要启用 " + pos.PosNO + " 吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                pos.UpdateTo(Table.PosS.EnumEnable.启用);
                            break;
                    }
                    break;

                default:
                    selectedMenu.DataTable = uCPagePanel1.SelectedItem as FCNS.Data.Table.DataTableS;
                    pluginManager.LoadPlugin(DbDefine.baseDir + selectedMenu.DllFile, null, selectedMenu.TableText, selectedMenu.DataTable, selectedMenu.Tag);
                    break;
            }
        }

        private void PagePanelModeChanged(Utility.UC.UCPagePanel.EnumMode ee)
        {
            if (selectedMenu != null)
                selectedMenu.UserParams.Mode = ee;
        }

        private void TreeViewNodeClick()
        {
            if (string.IsNullOrEmpty(selectedMenu.DllFile))
                return;
            if (selectedMenu.MustRefreshSubItem)
            {
                buttonNew.IsEnabled = true;
                return;
            }
            ConfigDataGridTopWhenSelectedMenuChanged();
            ConfigUCPagePanelWhenSelectedMenuChanged();
            Table.SysConfig.SysConfigParams._Temp_uint = 0;
            BeginBindData();
        }

        private void ConfigDataGridTopWhenSelectedMenuChanged()
        {
            if (selectedMenu == null)
            {
                buttonNew.IsEnabled = false;
                return;
            }

            //button_print.IsEnabled = selectedMenu.CanPrint;
            //button_import.IsEnabled = selectedMenu.CanImport;
            buttonNew.IsEnabled = selectedMenu.CanNew;
            //if (selectedMenu.NewButtonText != string.Empty)
            //    buttonNew.Content = selectedMenu.NewButtonText;
            //else
            //    buttonNew.Content = "创建";

        }

        private void ConfigUCPagePanelWhenSelectedMenuChanged()
        {
            uCPagePanel1.ContextMenu.Items.Clear();
            if (selectedMenu.ContextMenuItems != null)
            {
                foreach (MenuItem mi in selectedMenu.ContextMenuItems)
                    uCPagePanel1.ContextMenu.Items.Add(mi);
            }

            uCPagePanel1.Init(selectedMenu.UserParams, selectedMenu.DataTempleteName);
        }

        //private void EventImport()
        //{
        //    FCNS.Data.Interface.DataIO io = null;
        //    switch (selectedMenu.TableText)
        //    {
        //        case DataTableText.客户:
        //            break;
        //        default:
        //            MessageWindow.Show("当前类别不支持数据导入");
        //            break;
        //    }
        //    if (io != null)
        //        io.Import(string.Empty);
        //}

        /// <summary>
        /// 如果系统日期被更改了，就自动注销系统。
        /// </summary>
        private void InitCheckDateIsChangedEvent()
        {
            Microsoft.Win32.SystemEvents.TimeChanged += (ss, ee) =>
                {
                    if (DateTime.Now.Date != Table.SysConfig.SysConfigParams.LastLoginDate.Date)
                        LoginOff();
                };
        }

        #region CPU event

        void CPU_ShenHeTableObject(FCNS.Data.Interface.IDataTable table)
        {
            BeginBindData();
        }

        void CPU_InsertTableObject(FCNS.Data.Interface.IDataTable table)
        {
            if (selectedMenu.MustRefreshSubItem)
                TopMenuClick(Table.SysConfig.EnumModel.公寓租赁);

            BeginBindData();
        }

        //void CPU_DeleteTableObject(FCNS.Data.Interface.IDataTable table)
        //{
        //    Debug.Assert(uCPagePanel1.Items != null);
        //        ((IList)uCPagePanel1.Items).Remove(table);
        //}

        void CPU_ReloadTableList(FCNS.Data.Interface.IDataTable table)
        {
            if (selectedMenu.MustRefreshSubItem)
                TopMenuClick(Table.SysConfig.EnumModel.公寓租赁);

            BeginBindData();
        }

        private void WuLiu(Table.StoreOrderS order)
        {
            if (Table.SysConfig.SysConfigParams.UseWuLiuS && Table.UserS.LoginUser.GetAuthority(DataTableText.仓库物流跟踪) > Table.UserS.EnumAuthority.查看)
                pluginManager.LoadPlugin("WuLiuS.dll", null, DataTableText.仓库物流跟踪, null, order.OrderNO);
        }
        #endregion



        private void ThisClose()
        {
            DoubleH.Utility.Net.NetUtility.CloseNet();

            MessageFormClose();
            pluginManager.UnloadAllExtension();
            ConfigSerializer.SaveConfig(DoubleHConfig.UserConfig, Table.UserS.LoginUser.Id);
            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);
        }

        #region MessageForm
        private void InitMessageForm()
        {
            messageForm.Owner = this;
            messageForm.Width = DoubleHConfig.UserConfig.MessageFormWidth;
            messageForm.Height = DoubleHConfig.UserConfig.MessageFormHeight;
            ShowMessageForm();
            MessageFormLocation();
        }

        private void MessageFormClose()
        {
            if (messageForm == null)
                return;

            DoubleHConfig.UserConfig.MessageFormWidth = messageForm.Width;
            DoubleHConfig.UserConfig.MessageFormHeight = messageForm.Height;
            messageForm.Close();
        }

        private void MessageFormLocation()
        {
            if (messageForm == null)
                return;

            if (this.WindowState == WindowState.Maximized)
            {
                messageForm.Left = SystemParameters.FullPrimaryScreenWidth - messageForm.Width;
                messageForm.Top = (SystemParameters.FullPrimaryScreenHeight - messageForm.Height) / 2;
            }
            else
            {
                messageForm.Left = this.Width - messageForm.Width + this.Left;
                messageForm.Top = (this.Height - messageForm.Height) / 2 + this.Top;
            }
        }

        private void HideMessageForm()
        {
            messageForm.Hide();
        }

        private void ShowMessageForm()
        {
            if (DoubleHConfig.UserConfig.ShowMessageWindow)
                messageForm.Show();
        }
        #endregion

        #region Net
        void TextMessageReceived(FSLib.IPMessager.Entity.MessageEventArgs e)
        {
            messageForm.AddMessage(e.Message.UserName + "：" + e.Message.NormalMsg);
        }

        private void OnlineHost(FSLib.IPMessager.Entity.OnlineHost.HostEventArgs e)
        {
            messageForm.AddMessage(e.Host.NickName + " 上线");
            CheckDHserver();
        }

        private void OfflineHost(FSLib.IPMessager.Entity.OnlineHost.HostEventArgs e)
        {
            messageForm.AddMessage(e.Host.NickName + " 下线");
            CheckDHserver();
        }

        private void CheckDHserver()
        {
            if (DoubleH.Utility.Net.NetUtility.ServerHost != null)
                netState.ImageSource = new BitmapImage(new Uri(@"Pack://application:,,,/DoubleH;component/Images/yesnet_64.png"));
            else
                netState.ImageSource = new BitmapImage(new Uri(@"Pack://application:,,,/DoubleH;component/Images/nonet_64.png"));
        }
        #endregion

        ////公共
        //    /// <summary>
        //    /// 添加菜单
        //    /// </summary>
        //    public void AddItemToExpanderMenu(Button btn)
        //    {
        //        MessageBox.Show((expanderConfig.Content is Grid).ToString());
        //    }
    }
}